<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		
		<script>
			
			const dataList = [
			  { id: 1, name: 'A', children: [] },
			  { id: 2, name: 'B', children: [
				{ id: 3, name: 'C', children: [] },
			    { id: 4, name: 'D', children: [
			      { id: 5, name: 'E', children: [] }
			    ] }
			  ] },
			  { id: 6, name: 'F', children: [] }
			];
			
			let arr=[];
			function callback(data,level,parentData) {
				let obj={};		
				obj['name']=data['name']
				obj['id']=data['id']
				 if(parentData==null){
					 obj['pid']=0;
				 }else{
					  obj['pid']=parentData['id'];
				 }		
				  arr.push(obj);
			}
			
			
			
			recursiveProcess(dataList, 'children', callback);
			console.log(arr)
			let tree=createHierarchy(arr,'pid',0,'id','children');
			console.log(tree);
			
			function recursiveProcess(dataList, childField, callback, level = 0,parentData=null) {
			  // 遍历数据列表
			  dataList.forEach(data => {
			    // 执行回调函数，并传递层级信息
			    callback(data, level,parentData);
			    // 检查是否存在child字段且具有数据
			    if (data[childField] && data[childField].length > 0) {
			      // 递归调用自身处理子级数据，传递增加的层级信息
			      recursiveProcess(data[childField], childField, callback, level + 1,data);
			    }
			  });
			}
			
			
			function createHierarchy(dataList, parentIdField, parentIdValue, childIdField, childField) {
			  const tree = [];
			
			  // 递归查找以parentIdValue作为父级的数据项
			  function findChildren(parentIdValue) {
			    const children = [];
			
			    for (let i = 0; i < dataList.length; i++) {
			      const data = dataList[i];
			
			      // 判断是否为当前parentIdValue的子级
			      if (data[parentIdField] === parentIdValue) {
			        const child = {
			          ...data,
			          [childField]: findChildren(data[childIdField])
			        };
			
			        children.push(child);
			      }
			    }
			
			    return children;
			  }
			
			  // 查找顶级数据项，并开始递归构建层级结构
			  for (let i = 0; i < dataList.length; i++) {
			    const data = dataList[i];
			
			    if (data[parentIdField] === parentIdValue) {
			      const item = {
			        ...data,
			        [childField]: findChildren(data[childIdField])
			      };
			
			      tree.push(item);
			    }
			  }
			
			  return tree;
			}
			
			
				
		</script>
	</body>
</html>